package com.TT.poi.easy;

import com.TT.poi.ExcelWrite;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 具体可参考 https://www.yuque.com/easyexcel/doc/read
 */
public class EasyExcelWriteTest {

    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 10; i++) {
            DemoData demoData = new DemoData();
            demoData.setString("字符串" + i);
            demoData.setDate(new Date());
            demoData.setDoubleData(0.56);
            list.add(demoData);
        }
        return list;
    }


    //根据list写入excel
    @Test
    public void simpleWrite() throws IOException {

        //写法1
        //String fileName = getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        //这里需要指定写用哪个class去写，然后写到第一个sheet，名字为模板，然后文件流就会会自动关闭
        //如果这里想使用03 则 传入excelType参数即可
        //EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

        //写法2
        String fileName = getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        //这里需要指定写用哪个class去写
        ExcelWriter excelWrite = EasyExcel.write(fileName,DemoData.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
        excelWrite.write(data(),writeSheet);
        ///千万别忘记finish 会帮忙关闭流
        excelWrite.finish();


    }



    /**
     * 最简单的读
     * <p>1. 创建excel对应的实体对象 参照{@link DemoData}
     * <p>2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link DemoDataListener}
     * <p>3. 直接读即可
     */
    @Test
    public void simpleRead() throws IOException {
        // 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
        // 写法1：
        String fileName = getPath() + "simpleWrite1587810104503.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
        // 写法2：
        /*fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
        ExcelReader excelReader = EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        excelReader.finish();*/
    }


    /**
     * 获取项目路径
     *
     * @throws IOException
     */
    private String getPath() throws IOException {
        File directory = new File("");
        return directory.getCanonicalPath() + File.separator;
    }

}
